<?php
/*
 * @Author: 哲学家乔布斯 <wuyangii@qq.com>
 * @Date: 2022-10-20 21:41:37
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-11-07 22:37:15
 * @Descripttion: 系统配置
 */

namespace app\api\controller\user\v1_0;


use think\Db;
class Orders extends Common
{
    protected $noNeedRight = ['index','calculate_handle','add'];
    /**
     * @Author: 哲学家乔布斯 <wuyangii@qq.com>
     * @brief: 
     * @return 
     * @Descripttion: 默认接口
     */    
    public function index(){
   
        $data = $this->calculate_handle();
        return self::successResult("成功",[
            'bus' => $data['bus'],
            'goods' => $data['goods'],
            'money' => $data['money'],
            'num' => count($data['goods']),
            'user_address' => (new \app\common\model\User())->where(['id' => $this->UserInfo['id']])->field(['name','mobile'])->find(),
        ]);
    }
    /**
     * @Author: 哲学家乔布斯 <wuyangii@qq.com>
     * @brief: 
     * @return 
     * @Descripttion: 预结算订单
     */ 
   public function calculate_handle(){
        $param = request()->param();
        $sku_data = json_decode($param['sku_data'],true);
        $sku_data_id = array_column($sku_data,"sku_id");
        $bus = (new \app\common\model\Bus())
                ->where(['id' => $this->bus_id])
                ->field(['address','nickname','phone'])
                ->find();
        $goods = (new \app\common\model\AgentGoodsCart())
                    ->alias('cart')
                    ->join("{$this->tdb}agent_goods_sku agent_goods_sku","agent_goods_sku.id = cart.goods_sku_id")
                    ->join("{$this->tdb}goods goods","goods.id = agent_goods_sku.goods_id")
                    ->join("{$this->tdb}goods_sku goods_sku","goods_sku.id = agent_goods_sku.goods_sku_id")
                    ->where([
                        'cart.user_id' => $this->UserInfo['id'],
                        'cart.agent_id' => $this->agent_id,
                        'cart.bus_id' => $this->bus_id,
                        ]) 
                    ->where('cart.goods_sku_id','in',$sku_data_id)
                    ->field([
                        'agent_goods_sku.id as sku_id',
                        'goods.img',
                        'goods.title',
                        'agent_goods_sku.money',
                        'cart.num',
                        'cart.id cart_id',
                        'goods_sku.stock'
                    ])
                    ->append(['is_stock'])
                    ->withAttr("is_stock",function($value,$data){
                        if($data['stock'] < $data['num']){
                            return [
                                'title' => '该商品库存不足',
                                'is_stock' => 0,
                            ];
                        }else{
                            return [
                                'title' => '',
                                'is_stock' => 1,
                            ];
                        }
                    })
                    ->select()->toArray();

        if(empty($goods)){
            return self::errorResult("购物车商品不存在");
        }
        #计算金额
        $money = 0;
        foreach ($goods as $key => $value) {
                $money += ($value['money'])*$value['num'];
        }
        return [
            'bus' => $bus,
            'goods' => $goods,
            'money' => [
                'money' => number_format($money,2),
            ]
        
        ];
   }
    /**
     * @Author: 哲学家乔布斯 <wuyangii@qq.com>
     * @brief: 
     * @return 
     * @Descripttion: 提交订单
     */ 
    public function add(){
        $data = $this->calculate_handle();
        $order_on = 'U' . date('YmdHis') . rand(1000, 9999);
        
        $money = $data["money"];
        $goods = $data['goods'];
        foreach ($goods as $key => &$va) {
             if($va['is_stock'] == 0){
                unset($va);
             }
        }
        if($this->is_close == 1){
            return self::errorResult("当前商家已经休息！！！");
        }
        if(empty($goods)){
            return self::errorResult("商品不存在！可能部分商品已经超出库存");
        }
        $user_phone  = request()->param('user_phone');
        $user_name  = request()->param('user_name');
        $user = (new \app\common\model\User())->where(['id' => $this->UserInfo['id']])->find();
        $bus = (new \app\common\model\Bus())->where(['id' => $this->bus_id])->find();
        Db::startTrans();
        try{
            $message = "订单创建失败,请重试";
            $process = true;
            $share_bus_money = 0;
            $user_bus_money = 0;
          
            foreach ($goods as $key => $val) {
                    $share_bus_money = (new \app\common\model\AgentGoodsSku())->where(['id' => $val['sku_id']])->value('share_bus_money') * $val['num'];
                    $user_bus_money = (new \app\common\model\AgentGoodsSku())->where(['id' => $val['sku_id']])->value('user_bus_money') * $val['num'];
            }
            if(!preg_match('/^1[3-9]\d{9}$/', $user_phone)){
                $message = "手机号格式不正确,请重试";
                $process = false;
            }
            (new \app\common\model\User())->where(['id' => $this->UserInfo['id']])->update([
                'name' => empty($user_name) ? '' : $user_name,
                'mobile' => empty($user_phone) ? '' : $user_phone,
            ]);
         
            $order_id = Db::table("{$this->tdb}user_orders")->insertGetId([
                'user_id' => $this->UserInfo['id'],
                'on' => $order_on,
                'addtime' => time(),
                'state' => 0,
                'money' => $money['money'],
                'money_cost' => $money['money'],
                'agent_id' => $this->agent_id,
                'bus_id' => $this->bus_id,
                'user_phone' => $user_phone,
                'user_name' => $user_name,
                'num' => count($goods),
                'bus_smoney' => $share_bus_money,
                'user_smoney' => empty($user['share_user_id']) ? 0 : $user_bus_money,
                'share_user_id' => $user['share_user_id'],
                'bus_address' => $bus['address'],
                'bus_nickname' => $bus['nickname'],
                'batch' => date("Ymd"),
            ]);
          
            if(!$order_id){
                $message = "主订单创建失败,请重试";
                $process = false;
            }
            $sku_data = [];
            #--------------创建子订单-------------------------------------
            $sku_arr_id = [];
            
            foreach ($goods as $key => $value) {
                $sku_arr_id[] = $value['sku_id']; 
                $goodss =  (new \app\common\model\AgentGoodsSku())
                            ->alias("agent_goods_sku")
                            ->join("{$this->tdb}goods goods","goods.id = agent_goods_sku.goods_id")
                            ->join("{$this->tdb}goods_sku goods_sku","goods_sku.id = agent_goods_sku.goods_sku_id")
                            ->join("{$this->tdb}goods_cate cate","cate.id = goods.cate_id")
                            ->field([
                                'agent_goods_sku.id',
                                'goods.img',
                                'goods_sku.sku_title',
                                'goods.title as goods_title',
                                'goods.introduce',
                                'goods.supplier_id',
                                'agent_goods_sku.money',
                                'agent_goods_sku.money_primary',
                                'agent_goods_sku.goods_id',
                                'agent_goods_sku.goods_sku_id',
                                'agent_goods_sku.sales',
                                'agent_goods_sku.stock',
                                'agent_goods_sku.share_bus_money',
                                'agent_goods_sku.user_bus_money',
                                'cate.title as cate_title',
                                'cate.id as cate_id',
                                ])
                            ->where(['agent_goods_sku.id' => $value['sku_id']])
                            ->find();
             
                $sku_data[] = [
                    'goods_title' => $goodss['goods_title'],
                    'goods_sku_title' => $goodss['sku_title'],
                    'goods_id' => $goodss['goods_id'],
                    'goods_sku_id' => $goodss['goods_sku_id'],
                    'goods_cate_title' => $goodss['cate_title'],
                    'goods_cate_id' => $goodss['cate_id'],
                    'z_money' => $value['money'] * $value['num'],
                    'd_money' => $value['money'],
                    'num' => $value['num'],
                    'img' => $goodss['img'],
                    'supplier_id' => $goodss['supplier_id'],
                    'agent_goods_id' => 0,
                    'agent_goods_sku_id' => $value['sku_id'],
                    'order_id' => $order_id,
                    'bus_smoney' => $goodss['share_bus_money'],
                    'user_smoney' => empty($user['share_user_id']) ? 0 : $goodss['user_bus_money'],
                    
                ];
              
         
                ##------------------修改商品库存------------------
                $goods = (new \app\common\model\GoodsSku())->where(['id' => $goodss['goods_sku_id']])->find();          
                $row = (new \app\common\model\GoodsSku())->where(['id' => $goodss['goods_sku_id'],'stock' => $goodss['stock']])->update([
                    'stock' => $goods['stock']-$value['num']
                ]);
                if(!$row){
                    $message = "订单创建失败,库存修改失败";
                    $process = false;
                }
            }
            #-------删除购物车-------------
            $row = (new \app\common\model\AgentGoodsCart())->where([
                        'bus_id' => $this->bus_id,
                        'agent_id' => $this->agent_id,
                        'user_id' => $this->UserInfo['id'],
                        ])->whereIn('goods_sku_id',$sku_arr_id)->delete();
            if(!$row){
                $message = "订单创建失败，购物车清除失败".$value['sku_id'];
                $process = false;
            }
            $row = (new \app\common\model\UserOrdersGoods())->insertAll($sku_data);
            if(!$row){
                $message = "子订单创建失败,请重试";
                $process = false;
            }
            #--------------end---创建子订单end-------------------------------------
           
            
            if ($process !== false) {
                Db::commit(); // 提交事务
            } else {
                Db::rollback(); // 回滚事务
            }
         } catch (\Exception $e) {
            $process = false;
            $message = $e->getMessage();
            Db::rollback(); // 回滚事务
        }
        if ($process !== false) {
            return self::successResult("",['order_id' => $order_id]);
        } else {
            return self::errorResult($message);
        }
    }
    
    

}
